package com.woniuxy.consumer;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.woniuxy.entity.KillOrder;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.util.RabbitmqConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author ：CuiYC
 * @description：
 * @date ：Created in 2025/3/20 17:16
 * @modified By：
 *  *  *  * 消费者重复问题
 *  *  *  * 由于网络原因，消费者消费完后应答失败。而它以为消费成功，直接消费新的（队列原来的）消息。
 *  *  *  * 这直接导致同一消息被重复消费。
 *  *  *  * 怎么解决？
 *  *  *  * 1.消息发送者发送消息时，设置消息的过期时间
 *
 *  *  *  * 1.生产者在发送消息是，获取该消息的唯一信息，存入redis中
 *  *  *  * 2.消费者消费消息时，先判断redis中是否有该消息，有则不处理，没有则处理。
 */
@Component
public class AddKillOrderConsumer {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RabbitListener(queues = RabbitmqConst.ADD_KILL_BOOK_QUEUE)
    public void receive(String msg, Channel channel, Message message) {
        try {

            KillOrder killOrder = JSON.parseObject(msg, KillOrder.class);
            if(redisTemplate.delete("killOrderNum:"+killOrder.getKillOrderNum())){
                orderMapper.addKillOrder(killOrder);
            }


            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }
}
